<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

class Order extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
    }

    /**
     * 订单列表
     */
    public function index()
    {
        $this->relationSearch = false;
        $this->request->filter(['strip_tags', 'trim']);
        
        // 获取所有工程师
        $engineers = Db::name('engineer')->field('id, name, mobile, area, tags')->select();
        $this->view->assign('engineers', $engineers);
        
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            try {
                // 获取基础参数
                $sort = $this->request->get('sort', 'id');
                $order = $this->request->get('order', 'desc');
                $offset = $this->request->get('offset', 0);
                $limit = $this->request->get('limit', 10);
                $search = $this->request->get('search', ''); // 新增search参数
                
                // 验证排序参数
                $sort = in_array($sort, ['id', 'create_time']) ? $sort : 'id';
                $order = strtoupper($order) === 'ASC' ? 'ASC' : 'DESC';
                
                // 构建原生SQL查询
                $where = [];
                $params = [];
                
                // 处理标准过滤条件
                $filter = $this->request->get('filter', '');
                $op = $this->request->get('op', '');
                
                if ($filter && $op) {
                    $filterData = json_decode(urldecode($filter), true) ?: [];
                    $opData = json_decode(urldecode($op), true) ?: [];
                    
                    foreach ($filterData as $field => $value) {
                        $operator = $opData[$field] ?? '=';
                        
                        if (strtoupper($operator) === 'LIKE') {
                            $where[] = "`{$field}` LIKE ?";
                            $params[] = "%{$value}%";
                        } else {
                            $where[] = "`{$field}` {$operator} ?";
                            $params[] = $value;
                        }
                    }
                }
                
                // 新增：处理全局搜索条件
                if (!empty($search)) {
                    $searchFields = [
                        '订单号', '标签', '业务类型', '物流单号', '客户订单号', '集配订单号', '服务单号', '安装网点', '安装网点编码',
                        '定制单号', '收货人名称', '收货人电话1', '收货人虚拟电话', '终端应签收时间'
                    ];
                    
                    $searchConditions = [];
                    foreach ($searchFields as $field) {
                        $searchConditions[] = "`{$field}` LIKE ?";
                        $params[] = "%{$search}%";
                    }
                    
                    if (!empty($searchConditions)) {
                        $where[] = '(' . implode(' OR ', $searchConditions) . ')';
                    }
                }
                
                // 构建完整WHERE子句
                $whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
                
                // 构建主查询
                $sql = "SELECT * FROM `fa_order` {$whereClause} ORDER BY `{$sort}` {$order} LIMIT {$offset}, {$limit}";
                
                // 执行查询
                $list = Db::query($sql, $params);
                
                // 获取总数
                $countSql = "SELECT COUNT(*) AS count FROM `fa_order` {$whereClause}";
                $total = Db::query($countSql, $params)[0]['count'];
                
                // 定义可见字段
                $visibleFields = [
                    'id', '订单号', '标签', '业务类型', '物流状态', '服务状态',
                    '是否预约', '是否派工', '是否代收', '用户原始期望配送时间',
                    '终端应签收时间', '网点预约时间', '配送工程师','收货人名称', '收货人电话1', '收货人虚拟电话',
                    '收货人详细地址','客户订单号', '运单号',
                    '集配订单号', '服务单号', '安装网点', '安装网点编码',
                    '定制单号', '定制类型', '订单类型', '业务模式',
                    '应取件出库时间', '物流单号', '是否回访','品牌','品类','是否需送装一体',
                    '信息员备注', '工程师备注','结算金额','工单状态'
                ];
                
                // 过滤结果字段
                $filteredList = array_map(function($item) use ($visibleFields) {
                    return array_intersect_key($item, array_flip($visibleFields));
                }, $list);
                
                return json([
                    'total' => $total,
                    'rows' => $filteredList
                ]);
                
            } catch (Exception $e) {
                trace([
                    'error' => $e->getMessage(),
                    'sql' => $sql ?? '',
                    'params' => $params ?? [],
                    'request' => $this->request->get()
                ], 'error');
                
                return json(['total' => 0, 'rows' => []]);
            }
        }
        
        return $this->view->fetch();
    }

     /**
     * 订单详情
     */
    public function detail($ids = null)
    {
        $ids = $this->request->get('id', '');
        $row = model('Order')->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑订单
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                $result = false;
                Db::startTrans();
                try {
                    // 使用原生SQL更新，避免中文字段名问题
                    $sql = "UPDATE `fa_order` SET ";
                    $updateParts = [];
                    $sqlParams = [];
                    
                    foreach ($params as $field => $value) {
                        if ($field === 'id') {
                            continue;
                        }
                        $updateParts[] = "`{$field}` = ?";
                        $sqlParams[] = $value;
                    }
                    
                    $sql .= implode(", ", $updateParts);
                    $sql .= " WHERE `id` = ?";
                    $sqlParams[] = $ids;
                    
                    // 执行更新
                    $result = Db::execute($sql, $sqlParams);
                    
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 字段映射定义 - 精简版，只保留edit.html中实际使用的字段
$fieldMapping = [
    'id' => 'id',
    '订单号' => 'order_number',
    '标签' => 'tag',
    '业务类型' => 'business_type',
    '物流状态' => 'logistics_status',
    '用户原始期望配送时间' => 'expected_delivery_time',
    '终端应签收时间' => 'terminal_receipt_time',
    '配送工程师' => 'delivery_engineer',
    '收货人名称' => 'receiver_name',
    '收货人电话1' => 'receiver_phone1',
    '收货人电话2' => 'receiver_phone2',
    '收货人虚拟电话' => 'receiver_virtual_phone',
    '收货人详细地址' => 'receiver_address',
    '客户订单号' => 'customer_order_number',
    '运单号' => 'waybill_number',
    '商品名称' => 'product_name',
    '订单来源平台' => 'order_source_platform',
    '关联单号' => 'related_order_number',
    '工单号' => 'work_order_number',
    '下单人信息' => 'orderer_information',
    '信息员备注' => 'info_officer_remarks',
    '工程师备注' => 'engineer_remarks',
];
        
        // 反向映射(用于表单提交时将英文字段名转回中文字段名)
        $reverseMapping = array_flip($fieldMapping);
        
        // 将数据转为数组
        $rowArray = $row ? $row->toArray() : [];
        
        // 创建映射后的数据
        $mappedRow = [];
        foreach ($rowArray as $key => $value) {
            if (isset($fieldMapping[$key])) {
                $mappedRow[$fieldMapping[$key]] = $value;
            } else {
                $mappedRow[$key] = $value;
            }
        }
        
        // 将原始数据和映射数据都传给视图
        $this->view->assign("row", $rowArray);  // 原始数据(中文字段名)
        $this->view->assign("mappedRow", $mappedRow);  // 映射后的数据(英文字段名)
        $this->view->assign("fieldMapping", $fieldMapping);  // 字段映射关系
        $this->view->assign("reverseMapping", $reverseMapping);  // 反向映射关系
        
        return $this->view->fetch();
    }

    /**
     * 获取工程师列表
     * @return \think\response\Json
     */
    public function getEngineers()
    {
        if ($this->request->isAjax()) {
            $engineers = Db::name('engineer')
                ->field('id, name, mobile, area, tags')
                ->select();
            
            // 处理tags字段，确保前端显示正常
            foreach ($engineers as &$engineer) {
                // 如果tags是空字符串，设置一个默认值
                if (empty($engineer['tags'])) {
                    $engineer['tags'] = '未设置';
                }
            }
            
            return json([
                'code' => 1,
                'msg' => '',
                'data' => $engineers
            ]);
        }
        
        $this->error(__('Invalid request'));
    }


    /**
     * 分配工程师（单个订单）
     */
    public function assignEngineer()
    {
        $id = $this->request->post('id');
        $engineerId = $this->request->post('engineer_id');
        
        if (!$id || !$engineerId) {
            $this->error('参数错误');
        }
        
        // 获取工程师信息
        $engineer = Db::name('engineer')->where('id', $engineerId)->find();
        if (!$engineer) {
            $this->error('工程师不存在');
        }
        
        Db::startTrans();
        try {
            // 使用原生SQL更新订单的配送工程师字段
            $sql = "UPDATE `fa_order` SET `配送工程师` = ? WHERE `id` = ?";
            $count = Db::execute($sql, [$engineer['name'], $id]);
            
            Db::commit();
            $this->success('成功分配订单给工程师：' . $engineer['name']);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('分配失败: ' . $e->getMessage());
        }
    }

    /**
     * 批量分配工程师
     */
    public function batchAssignEngineer()
    {
        $ids = $this->request->post('ids');
        $engineerId = $this->request->post('engineer_id');
        
        if (!$ids || !$engineerId) {
            $this->error('参数错误');
        }
        
        // 转换ids为数组
        if (!is_array($ids)) {
            $ids = explode(',', $ids);
        }
        
        // 获取工程师信息
        $engineer = Db::name('engineer')->where('id', $engineerId)->find();
        if (!$engineer) {
            $this->error('工程师不存在');
        }
        
        Db::startTrans();
        try {
            // 使用原生SQL更新订单的配送工程师字段
            $placeholders = rtrim(str_repeat('?,', count($ids)), ',');
            $sql = "UPDATE `fa_order` SET `配送工程师` = ? WHERE `id` IN ({$placeholders})";
            $params = array_merge([$engineer['name']], $ids);
            $count = Db::execute($sql, $params);
            
            Db::commit();
            $this->success('成功分配 ' . $count . ' 个订单给工程师：' . $engineer['name']);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('分配失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新工单状态
     */
    public function updateWorkStatus()
    {
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        
        if (!$id || !$status) {
            $this->error('参数错误');
        }
        
        Db::startTrans();
        try {
            // 使用原生SQL更新订单的工单状态字段
            $sql = "UPDATE `fa_order` SET `工单状态` = ? WHERE `id` = ?";
            $count = Db::execute($sql, [$status, $id]);
            
            Db::commit();
            $this->success('工单状态已更新为：' . $status);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('更新失败: ' . $e->getMessage());
        }
    }

    /**
     * 批量更新工单状态
     */
    public function batchUpdateWorkStatus()
    {
        $ids = $this->request->post('ids');
        $status = $this->request->post('status');
        
        if (!$ids || !$status) {
            $this->error('参数错误');
        }
        
        // 转换ids为数组
        if (!is_array($ids)) {
            $ids = explode(',', $ids);
        }
        
        Db::startTrans();
        try {
            // 使用原生SQL更新工单状态
            $placeholders = rtrim(str_repeat('?,', count($ids)), ',');
            $sql = "UPDATE `fa_order` SET `工单状态` = ? WHERE `id` IN ({$placeholders})";
            $params = array_merge([$status], $ids);
            $count = Db::execute($sql, $params);
            
            Db::commit();
            $this->success('成功更新 ' . $count . ' 个工单状态为：' . $status);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('更新失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新结算金额
     */
    public function updateSettlement()
    {
        $id = $this->request->post('id');
        $amount = $this->request->post('amount');
        
        if (!$id || !isset($amount)) {
            $this->error('参数错误');
        }
        
        // 检查工单状态是否为已完工
        $order = Db::name('order')->where('id', $id)->field('`工单状态`')->find();
        if (!$order || $order['工单状态'] !== '已完工') {
            $this->error('只有已完工的工单才能修改结算金额');
        }
        
        Db::startTrans();
        try {
            // 使用原生SQL更新结算金额
            $sql = "UPDATE `fa_order` SET `结算金额` = ? WHERE `id` = ?";
            Db::execute($sql, [$amount, $id]);
            
            Db::commit();
            $this->success('结算金额已更新');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('更新失败: ' . $e->getMessage());
        }
    }

    /**
     * 更新信息员备注
     */
    public function updateRemark()
    {
        $id = $this->request->post('id');
        $remark = $this->request->post('remark');
        
        if (!$id) {
            $this->error('参数错误');
        }
        
        Db::startTrans();
        try {
            // 使用原生SQL更新信息员备注
            $sql = "UPDATE `fa_order` SET `信息员备注` = ? WHERE `id` = ?";
            Db::execute($sql, [$remark, $id]);
            
            Db::commit();
            $this->success('信息员备注已更新');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('更新失败: ' . $e->getMessage());
        }
    }
}